package com.bjfu.demo.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bjfu.demo.dao.ArticleMapper;
import com.bjfu.demo.dto.ArticleDto;
import com.bjfu.demo.entity.Article;
import com.bjfu.demo.entity.ArticleExample;

/**
 * @create 2021-02-22 10:45
 */
@Service
public class ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    public List<ArticleDto> selectAll() {
        List<Article> articles = articleMapper.selectByExample(null);
        ArrayList<ArticleDto> articleDtos = new ArrayList<>();
        for (Article article : articles) {
            ArticleDto articleDto = new ArticleDto();
            articleDto.copyFromArticleToArticleDto(article);
            articleDtos.add(articleDto);
        }
        return articleDtos;
    }

    public int publishArticle(ArticleDto articleDto) {
        Article article = new Article();
        article.setTitle(articleDto.getTitle());
        article.setContent(articleDto.getContent());
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        article.setIsDelete(0);//0表示未删除，1表示删除
        return articleMapper.insertSelective(article);
    }

    public int updateArticle(ArticleDto articleDto) {

        Article article = new Article();
        article.setTitle(articleDto.getTitle());
        article.setContent(articleDto.getContent());
        article.setUpdateTime(new Date());
        ArticleExample articleExample = new ArticleExample();
        articleExample.createCriteria().andIdEqualTo(articleDto.getId());
        return articleMapper.updateByExampleSelective(article, articleExample);
    }

    public int deleteArticleByArticleId(ArticleDto articleDto) {
        Article article = new Article();
        article.setIsDelete(1);
        article.setUpdateTime(new Date());
        article.setId(articleDto.getId());
        return articleMapper.updateByPrimaryKeySelective(article);
    }

    public List<ArticleDto> selectArticle(ArticleDto articleDto) {
        ArticleExample articleExample = new ArticleExample();
        articleExample.createCriteria().andTitleLike("%" + articleDto.getTitle() + "%");
        List<Article> articles = articleMapper.selectByExample(articleExample);
        ArrayList<ArticleDto> articleDtos = new ArrayList<>();
        for (Article article : articles) {
            ArticleDto temp = new ArticleDto();
            temp.copyFromArticleToArticleDto(article);
            articleDtos.add(temp);
        }
        return articleDtos;
    }


    public ArticleDto selectArticle(Integer articleId) {
        Article article = articleMapper.selectByPrimaryKey(articleId);
        ArticleDto articleDto = new ArticleDto();
        articleDto.copyFromArticleToArticleDto(article);
        return articleDto;
    }


}
